package com.btpn.custody.web.m003.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.time.DateUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;

import com.btpn.custody.common.Constant;
import com.btpn.custody.dao.IAccount;
import com.btpn.custody.dao.IBranch;
import com.btpn.custody.dao.IUser;
import com.btpn.custody.entity.Area;
import com.btpn.custody.entity.Branch;
import com.btpn.custody.entity.User;
import com.btpn.custody.web.m003.model.Report03Model;
import com.btpn.infra.utils.MyDateUtils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

@ParentPackage(value="custody")
@Results({
	@Result(name="input", location="t_report03_form")
})
@Validations(
	requiredStrings = {
		@RequiredStringValidator(type=ValidatorType.SIMPLE, fieldName="fromDate", message="From date must be choosed")
    }
)
public class Jasper03Action extends ActionSupport implements Preparable {

	/*=============================================== C O N S T A N T =========================================*/
	private static final long serialVersionUID = 6843029078769105454L;

	/*=============================================== M E M B E R =============================================*/
	@Autowired
	private IAccount accountDaoHibernate;

	@Autowired
	private IBranch branchDaoHibernate;

	@Autowired
	private IUser userDaoHibernate;

	private Map<String, Object> paramMap = new HashMap<String, Object>();
	private List<Branch> branchs;
	private List<Area> areas;
	private String fromDate;
	private String toDate;
	private Long branchId;
	private Long areaId;
	private List<Report03Model> reportModels;

	/*=============================================== B E H A V I O R =========================================*/
	public void init() {
		User user = userDaoHibernate.get(SecurityContextHolder.getContext().getAuthentication().getName());
		System.out.println("===========> user name: "+user.getArea().getName());
		// init branch
		if (user.getArea().isJakarta()) {
			branchs = branchDaoHibernate.findByAreaId(user.getArea().getId());
			Branch b = new Branch();b.setId(-1L);b.setName("all branch");
			branchs.add(0, b);
		} else {
			branchs = branchDaoHibernate.findByAreaId(user.getArea().getId());
		}
	}

	@SkipValidation
	@Action(value = "/report03-form", results = { @Result(name="success", location="t_report03_form") })
	public String execute() throws Exception {

		return SUCCESS;
	}

	@Action(value = "/report03", results = {
		@Result(name="success", type="jasper",
				params = {"location", "/jasper/report03.jasper", "dataSource", "reportModels", "reportParameters", "paramMap", "contentDisposition", "attachment", "format", "XLS", "documentName", "SLA Detail"}) ,
		@Result(name="none", type="redirectAction", params = {"actionName", "report03-form"} )
	})
	public String showReport03() throws Exception {

		Date from = MyDateUtils.strToDate(Constant.FORMAT_PRESENTATION, fromDate);
		Date to = MyDateUtils.strToDate(Constant.FORMAT_PRESENTATION, toDate);
		
		//string version for native 
		String strFrom =MyDateUtils.StringToStringFormatDate(Constant.FORMAT_PRESENTATION, Constant.FORMAT_REPORT, fromDate);
		String strTo =MyDateUtils.StringToStringFormatDate(Constant.FORMAT_PRESENTATION, Constant.FORMAT_REPORT, toDate);
		
		System.out.println("===>from: "+fromDate+" from: "+from+ "strFrom: "+strFrom);
		System.out.println("==>toDate: "+toDate+" to: "+to +"strTo: "+strTo);

		if (from == null) {
			addFieldError(fromDate, "Invalid date format");
			return NONE;
		}

		if (to == null) {
			to = DateUtils.addSeconds(DateUtils.addDays(from, 1), -1);
			//pada hari yang sama dengan from
			strTo=strFrom;
		} else {
			to = DateUtils.addSeconds(DateUtils.addDays(to, 1), -1);
		}
		
		//balik convert to String
//		strForm= MyDateUtils.StringToStringFormatDate(Constant.FORMAT_PRESENTATION, Constant.FORMAT_REPORT, from);
		User user = userDaoHibernate.get(SecurityContextHolder.getContext().getAuthentication().getName());
		reportModels = new ArrayList<Report03Model>(0);

		System.out.println("======>branchId: "+branchId);
		System.out.println("from: "+from);
		System.out.println("to: "+to);
//		reportModels=accountDaoHibernate.findByBranchDateRangeByModel(branchId, from, to);
		
		if (branchId==-1) {																// -1 : all branch
			System.out.println("-1 : all branch");
			reportModels=accountDaoHibernate.findByDateRangeByModel(strFrom, strTo);
			/*
			for (Account a : accountDaoHibernate.findAllByDateRange(from, to)) {
				reportModels.add(new Report03Model(
						a.getMasterData().getBranch().getCode(),
						a.getMasterData().getCIF().getCifSid(),
						a.getACCOUNT(),
						a.getACCOUNT_OPEN(),
						a.getCREATED_USER_ID(),
						a.getMasterData().getAPPROVED_USER(),
						a.getMasterData().getAPPROVED_DATE(),
						a.getMasterData().getWAIT_APPROVAL_USER(),
						a.getMasterData().getWAIT_APPROVAL_DATE(),
						a.getMasterData().getRECEIVED_USER(),
						a.getMasterData().getRECEIVED_DATE(),
						a.getMasterData().getTBO_USER(),
						a.getMasterData().getTBO_DATE(),
						a.getMasterData().getPROGRESS_USER(),
						a.getMasterData().getPROGRESS_DATE(),
						a.getMasterData().getSEND_EQ_DATE()));
			}*/
		} else if (branchId==-2) {														// -2 -> all branch in area
			System.out.println("-2 -> all branch in area");
			System.out.println("user area: "+user.getArea().getId());
			reportModels=accountDaoHibernate.findByAreaDateRangeByModel(user.getArea().getId(), strFrom, strTo);
			/*
			for (Account a : accountDaoHibernate.findByAreaDateRange(user.getArea().getId(), from, to)) {
				reportModels.add(new Report03Model(
						a.getMasterData().getBranch().getCode(),
						a.getMasterData().getCIF().getCifSid(),
						a.getACCOUNT(),
						a.getACCOUNT_OPEN(),
						a.getCREATED_USER_ID(),
						a.getMasterData().getAPPROVED_USER(),
						a.getMasterData().getAPPROVED_DATE(),
						a.getMasterData().getWAIT_APPROVAL_USER(),
						a.getMasterData().getWAIT_APPROVAL_DATE(),
						a.getMasterData().getRECEIVED_USER(),
						a.getMasterData().getRECEIVED_DATE(),
						a.getMasterData().getTBO_USER(),
						a.getMasterData().getTBO_DATE(),
						a.getMasterData().getPROGRESS_USER(),
						a.getMasterData().getPROGRESS_DATE(),
						a.getMasterData().getSEND_EQ_DATE()));
			}
			*/
		} else {																			// branch
			reportModels=accountDaoHibernate.findByBranchDateRangeByModel(branchId, strFrom, strTo);
			/*
			for (Account a : accountDaoHibernate.findByBranchDateRange(branchId, from, to)) {
				reportModels.add(new Report03Model(
						a.getMasterData().getBranch().getCode(),
						a.getMasterData().getCIF().getCifSid(),
						a.getACCOUNT(),
						a.getACCOUNT_OPEN(),
						a.getCREATED_USER_ID(),
						a.getMasterData().getAPPROVED_USER(),
						a.getMasterData().getAPPROVED_DATE(),
						a.getMasterData().getWAIT_APPROVAL_USER(),
						a.getMasterData().getWAIT_APPROVAL_DATE(),
						a.getMasterData().getRECEIVED_USER(),
						a.getMasterData().getRECEIVED_DATE(),
						a.getMasterData().getTBO_USER(),
						a.getMasterData().getTBO_DATE(),
						a.getMasterData().getPROGRESS_USER(),
						a.getMasterData().getPROGRESS_DATE(),
						a.getMasterData().getSEND_EQ_DATE()));
			}
			*/
		}
		
		if (reportModels.size()==0) {
			addActionMessage("Empty data");
			return NONE;
		}

		return SUCCESS;
	}

	@Override
	public void prepare() throws Exception {
		init();
	}

	/*=============================================== G E T T E R   &   S E T T E R ===========================*/
	public Long getBranchId() {
		return branchId;
	}

	public void setBranchId(Long branchId) {
		this.branchId = branchId;
	}

	public List<Report03Model> getReportModels() {
		return reportModels;
	}

	public void setReportModels(List<Report03Model> reportModels) {
		this.reportModels = reportModels;
	}

	public Long getAreaId() {
		return areaId;
	}

	public void setAreaId(Long areaId) {
		this.areaId = areaId;
	}

	public String getFromDate() {
		return fromDate;
	}

	public void setFromDate(String fromDate) {
		this.fromDate = fromDate;
	}

	public String getToDate() {
		return toDate;
	}

	public void setToDate(String toDate) {
		this.toDate = toDate;
	}

	public Map<String, Object> getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map<String, Object> paramMap) {
		this.paramMap = paramMap;
	}

	public List<Branch> getBranchs() {
		return branchs;
	}

	public void setBranchs(List<Branch> branchs) {
		this.branchs = branchs;
	}

	public List<Area> getAreas() {
		return areas;
	}

	public void setAreas(List<Area> areas) {
		this.areas = areas;
	}
}